package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.aliyun.GreenImageScan;
import com.heima.aliyun.GreenTextScan;
import com.heima.common.constants.PublishArticleConstants;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author zx
 * @date 2021/11/24 17:02
 */
@Service
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    WmNewsMapper wmNewsMapper;

    @Autowired
    AdminFeign adminFeign;

    @Value("${file.oss.web-site}")
    String webSite;

    @Autowired
    GreenImageScan greenImageScan;

    @Autowired
    GreenTextScan greenTextScan;

    @Autowired
    RabbitTemplate rabbitTemplate;


    /**
     * 自媒体文章审核
     * @param wmNewsid  自媒体文章id
     */
    @Override
    public void autoScan(Integer wmNewsid) {
        log.info("开始审核 id={}",wmNewsid);

        //1.判断id
        if (wmNewsid==null) {
            log.error("审核失败 查询不到该文章 ");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2 查询作者
        WmNews wmNews = wmNewsMapper.selectById(wmNewsid);
        if (wmNews==null) {
            log.error("审核失败，查询不到该文章作者   wmNewsid={}",wmNewsid);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3 文章状态
        if (!wmNews.getStatus().equals(WemediaConstants.WM_NEWS_SUMMIT_STATUS)) {
            log.error("审核状态不对   Status={}",wmNews.getStatus());
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }

        //4.开始审核
        Map<String,Object> textAndImages=TextAndImages(wmNews);

        // 4.1 DFA审核
        log.info("开始DFA审核");

        boolean result=sensitiveCode((String)textAndImages.get("content"),wmNews);
        if (!result) {
              log.error("敏感词审核失败");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);

        }

        log.info("开始阿里云文本审核");

        // 4.2  阿里云的文本审核   失败  状态2  不确定 状态3
        boolean isTextScan = handleTextScan((String)textAndImages.get("content"),wmNews);
        if(!isTextScan) {
            log.error("阿里云文本审核失败");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        log.info(" 阿里云内容审核通过  =======   ");


        log.info("开始阿里云图片审核")
        ;
        // 4.3  阿里云的图片审核   失败  状态2  不确定 状态3
        Object images = textAndImages.get("images");
        if(images!=null){
            boolean isImageScan =handleImageScan((List<String>)images,wmNews);
            if(!isImageScan) return;
            log.info(" 阿里云图片审核通过  =======   ");
        }

        // 5. 判断文章发布时间是否大于当前时间   状态 8
        upWmNewsStatus(wmNews,WmNews.Status.SUCCESS.getCode(),"审核成功");
        log.info("审核结束 id={}",wmNewsid);

        //6 发布
        log.info("开始发布");

        // 6.1 发布时间
        long publishTime = wmNews.getPublishTime().getTime();

        // 6.2当前时间
        long nowTime = new Date().getTime();
        long remainTime = publishTime - nowTime;

        // 6.3 发布文章
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                , wmNews.getId()
                , (message)->{                              // 延时消息 必设置
                    message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                    return message;
                }
        );
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());
    }

    /**
     * 阿里云图片审核
     * @param images  待审核的图片列表
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) {
        boolean flag = true;
        try {
            Map map = greenImageScan.imageUrlScan(images);
            String suggestion = (String)map.get("suggestion");
            switch (suggestion){
                case "block":
                    upWmNewsStatus(wmNews,WmNews.Status.FAIL.getCode(),"图片中有违规内容，审核失败");
                    flag = false;
                    break;
                case "review":
                    upWmNewsStatus(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"图片中有不确定内容，转为人工审核");
                    flag = false;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("阿里云图片审核出现异常 , 原因:{}",e.getMessage());
            upWmNewsStatus(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"阿里云内容服务异常，转为人工审核");
            flag = false;
        }
        return flag;
    }

    /**
     * 阿里云文本
     * @param content    block: 状态2    review: 状态3    异常: 状态3
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {

        boolean flag = true;

        try {
            Map map = greenTextScan.greenTextScan(content);

            String suggestion = (String)map.get("suggestion");

            switch (suggestion){
                case "block":
                    upWmNewsStatus(wmNews,WmNews.Status.FAIL.getCode(),"文本中有违规内容，审核失败");
                    flag = false;
                    break;
                case "review":
                    upWmNewsStatus(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"文本中有不确定内容，转为人工审核");
                    flag = false;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("阿里云文本审核出现异常 , 原因:{}",e.getMessage());
            upWmNewsStatus(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"阿里云内容服务异常，转为人工审核");
            flag = false;
        }
        return flag;
    }

    /**
     * 基于DFA 检测内容是否包含敏感词
     * @param content
     * @param wmNews
     * @return
     */
    private boolean sensitiveCode(String content, WmNews wmNews) {

        boolean flag = true;

        // 1. 查询出数据库中的敏感词
        ResponseResult<List<String>> Sensitivesresult = adminFeign.selectAllChannel();

        if(Sensitivesresult.getCode().intValue()!=0){
            log.error("远程调用失败");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,Sensitivesresult.getErrorMessage());
        }

        List<String> allSensitives = Sensitivesresult.getData();

        // 2. 将敏感词集合转发DFA数据模型
        SensitiveWordUtil.initMap(allSensitives);

        // 3. 检测敏感词
        Map<String, Integer> resultMap = SensitiveWordUtil.matchWords(content);

        if(resultMap!=null && resultMap.size() > 0){
            // 将文章状态改为2
            upWmNewsStatus(wmNews,WmNews.Status.FAIL.getCode(),"内容中包含敏感词: " + resultMap);
            flag = false;
        }

        return flag;
    }

    /**
     * 修改文章状态
     * @param wmNews
     * @param status
     * @param reason
     */
    private void upWmNewsStatus(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }


    /**
     * 抽取 文本内容  及 图片
     * @param wmNews  content  type:text     title
     * @return
     */
    private Map<String, Object> TextAndImages(WmNews wmNews) {

        log.info("开始审核文本内容");

        Map<String,Object> result=new HashMap<>();

        List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);

        //1 文本

        //1.1,文本内容
        if (StringUtils.isBlank(wmNews.getContent())) {
            log.error("文章内容为空  wmNews.getContent()={} ",wmNews.getId());
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }

        //1.2 抽取文章的文本
        String collectText = maps.stream()
                .filter(map -> "text".equals(map.get("type")))
                .map(map -> (String) map.get("value"))
                .distinct()
                .collect(Collectors.joining("_heimaleadnews_"));
//        List<String> collectText = maps.stream()
//                .filter(map -> "text".equals(map.get("type")))
//                .map(map -> (String) map.get("value"))
//                .distinct()
//                .collect(Collectors.toList());
        result.put("content",collectText);

        log.info("结束审核文本");
        log.info("开始审核图片");

        //2 图片
        //2.1 图片
//        if (StringUtils.isBlank(wmNews.getImages())) {
//            log.error("图片为空  wmNews.getImages()={} ",wmNews.getImages());
//            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
//        }

        //2.2抽取文章中图片
       List<String> collectImages= maps.stream().filter(map -> "images".equals(map.get("type")))
                .map(map -> (String) map.get("value"))
                .distinct()
                .collect(Collectors.toList());

       //2.3 抽取封面的图片
        List<String> coverImages = Arrays.stream(wmNews.getImages().split(",")).map(url -> webSite + url).distinct().collect(Collectors.toList());

        if (StringUtils.isBlank(wmNews.getImages())) {
            log.error("图片为空  wmNews.getImages()={} ",wmNews.getImages());
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        collectImages.addAll(coverImages);

        //2.4最终去重
        collectImages = collectImages.stream().distinct().collect(Collectors.toList());

        result.put("images",collectImages);
        log.info("结束审核图片");

        //3.返回最终
        return result;
    }
}
